package com.xywl.escort.view.farm;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.bigkoo.convenientbanner.listener.OnItemClickListener;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.trello.rxlifecycle2.LifecycleTransformer;
import com.xywl.escort.R;
import com.xywl.escort.adapter.NetworkImageHolderView;
import com.xywl.escort.adapter.ProjectAdapter;
import com.xywl.escort.base.BaseFragment;
import com.xywl.escort.bean.BannerResp;
import com.xywl.escort.bean.ProjectListResp;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import dagger.android.support.AndroidSupportInjection;
import qiu.niorgai.StatusBarCompat;
import timber.log.Timber;

public class FarmFragment extends BaseFragment implements FarmContract.View, SwipeRefreshLayout.OnRefreshListener {
    private static final String ARG_PARAM1 = "param1";
    @Inject
    FarmContract.Presenter mPresenter;

    @BindView(R.id.tv_title)
    TextView mTvTitle;

    ConvenientBanner mConvenientBanner;

    @BindView(R.id.recycler_project)
    RecyclerView mRecyclerProject;
    @BindView(R.id.swipeLayout)
    SwipeRefreshLayout mSwipeRefreshLayout;
    @BindView(R.id.progress_bar)
    ProgressBar mProgressBar;
    private ProjectAdapter mAdapter;

    private int pageNum = 1;
    private boolean isEnd = false;

    private List<ProjectListResp.DataBean.ListBean> mList = new ArrayList<>();

    public FarmFragment() {
        // Required empty public constructor
    }

    public static FarmFragment newInstance(String param1) {
        FarmFragment fragment = new FarmFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onAttach(Context context) {
        AndroidSupportInjection.inject(this);
        super.onAttach(context);
    }

    @Override
    public int getLayoutResId() {
        return R.layout.fragment_farm;
    }

    @Override
    protected void initView(@Nullable Bundle savedInstanceState) {
        mTvTitle.setText(getString(R.string.tab_farm));
        if (null != getActivity()) {
            StatusBarCompat.translucentStatusBar(getActivity(), true);
        }
        LinearLayoutManager manager = new LinearLayoutManager(this.getActivity());
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerProject.setLayoutManager(manager);

        View view = getLayoutInflater().inflate(R.layout.view_farm_header, (ViewGroup) mRecyclerProject.getParent(), false);
        mConvenientBanner = view.findViewById(R.id.convenientBanner);
        mAdapter = new ProjectAdapter(R.layout.item_project, mList);
        mAdapter.addHeaderView(view);
        mRecyclerProject.setAdapter(mAdapter);

        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                String projectId = mList.get(position).id;
                String title = mList.get(position).name;
                ARouter.getInstance().build("/xy/project/detail")
                        .withString("projectId", projectId)
                        .withString("title", title)
                        .navigation();
            }
        });

        mSwipeRefreshLayout.setOnRefreshListener(this);
        mSwipeRefreshLayout.setColorSchemeResources(R.color.colorAccent, R.color.colorPrimary, R.color.aid_prompt_color, R.color.colorBackground);
    }

    @Override
    protected void initData() {
        mPresenter.takeView(this);
        mPresenter.loadBanner();
        pageNum = 1;
        mPresenter.loadProject(pageNum);

        mAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                mSwipeRefreshLayout.setEnabled(false);
                mRecyclerProject.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mSwipeRefreshLayout.setEnabled(false);
                        if (isEnd) {
                            //数据全部加载完毕
                            mAdapter.loadMoreEnd();
                            mSwipeRefreshLayout.setEnabled(true);
                        } else {
                            //成功获取更多数据
                            mPresenter.loadProject(pageNum);
                        }
                    }
                }, 200);
            }
        }, mRecyclerProject);
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden) {
            Timber.e("FarmFragment onHiddenChanged hidden");
        } else {
            Timber.e("FarmFragment onHiddenChanged");
            mPresenter.loadBanner();
            pageNum = 1;
            mPresenter.loadProject(pageNum);
        }
    }

    @Override
    public boolean isActive() {
        return false;
    }

    @Override
    public <T> LifecycleTransformer<T> bindToLife() {
        return this.<T>bindToLifecycle();
    }

    @Override
    public void loadBannerSuccess(final BannerResp resp) {
        mSwipeRefreshLayout.setRefreshing(false);
        mProgressBar.setVisibility(View.GONE);
        mRecyclerProject.setVisibility(View.VISIBLE);
        if (null != resp.data) {
            List<BannerResp.DataBean> list = resp.data;
            List<String> bannerList = new ArrayList<>();
            for (BannerResp.DataBean bean : list) {
                bannerList.add(bean.imgUrl);
            }
            mConvenientBanner.setPages(new CBViewHolderCreator() {
                @Override
                public NetworkImageHolderView createHolder() {
                    return new NetworkImageHolderView();
                }
            }, bannerList).setPageIndicator(new int[]{
                    R.mipmap.home_banner2,
                    R.mipmap.home_banner1})
                    .setPageIndicatorAlign(ConvenientBanner.PageIndicatorAlign.CENTER_HORIZONTAL)
                    .setOnItemClickListener(new OnItemClickListener() {
                        @Override
                        public void onItemClick(int position) {
                            List<BannerResp.DataBean> bannerData = resp.data;
                            BannerResp.DataBean listBean = bannerData.get(position);
                            if (null != listBean) {
                                switch (listBean.linkType) {
                                    case 1:
                                        ARouter.getInstance().build("/xy/web/links")
                                                .withString("url", listBean.linkContent)
                                                .withString("title", getString(R.string.app_name)).navigation();
                                        break;
                                    case 2:
                                        ARouter.getInstance().build("/xy/project/detail")
                                                .withString("projectId", listBean.linkContent)
                                                .withString("title", "项目详情")
                                                .navigation();
                                        break;
                                    case 3:
                                        String content = listBean.linkContent;
                                        if (!TextUtils.isEmpty(content)) {
                                            ARouter.getInstance().build("/xy/product/detail").withString("spuId", content).navigation();
                                        }
                                        break;
                                    default:
                                        break;
                                }
                            }
                        }
                    })
                    .setCanLoop(bannerList.size() > 1);
            if (bannerList.size() > 1) {
                mConvenientBanner.startTurning(5000);
            }
        }
    }

    @Override
    public void loadBannerFailure() {
        mSwipeRefreshLayout.setRefreshing(false);
        mProgressBar.setVisibility(View.GONE);
        mRecyclerProject.setVisibility(View.VISIBLE);
        Timber.tag("FarmFragment").e("loadBannerFailure");
    }

    @Override
    public void loadProjectSuccess(ProjectListResp.DataBean dataBean) {
        mSwipeRefreshLayout.setRefreshing(false);
        mProgressBar.setVisibility(View.GONE);
        mRecyclerProject.setVisibility(View.VISIBLE);
        if (pageNum == 1) {
            mList.clear();
        }
        if (pageNum >= dataBean.pages) {
            isEnd = true;
        } else {
            isEnd = false;
            pageNum += 1;
        }
        if (null != dataBean.list) {
            mList.addAll(dataBean.list);
        }
        mAdapter.setNewData(mList);
        mAdapter.loadMoreComplete();
        mSwipeRefreshLayout.setEnabled(true);
    }

    @Override
    public void loadProjectFailure() {
        mSwipeRefreshLayout.setRefreshing(false);
        mProgressBar.setVisibility(View.GONE);
        mRecyclerProject.setVisibility(View.VISIBLE);
    }

    @Override
    public void onRefresh() {
        mAdapter.setEnableLoadMore(false);
        mPresenter.loadBanner();
        pageNum = 1;
        mPresenter.loadProject(pageNum);
    }
}
